var createError = require('http-errors');//创建HTTP错误对象
var express = require('express');
var path = require('path');//path是路径模块，用于处理文件和目录的路径。
var cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
require('express-async-errors');//async/await 如果不捕获，直接报错误，不返回给用户信息，没办法拦截
var log4Util= require('./utils/logUtil/log4Util');//日志打印
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');//设置视图模板引擎

app.use(express.json());//负载均衡
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());//加载解析cookie的中间件
app.use("/public",express.static(path.join(__dirname, 'public')));//静态资源---保存到git上的
app.use("/static",express.static(path.join(__dirname, 'static')));//静态资源---一般是业务生成的文件，不保存到git上

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization,access-token');
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});
app.use(log4Util.netLog);
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    log4Util.errorLog(err,req,res);
    // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
